﻿using Shared.DI;
using Shared.Loggers;
using StructureMap;
using StructureMap.Pipeline;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DI
{
    public static class Bootstrapper
    {
        public static Container CurrentContainer { get; set; }        

        public static void Init(ILifecycle serviceLifecycle, string connectionString)
        {
            try
            {                
                CurrentContainer = new Container(x =>
                {                                        
                    x.AddRegistry(new AdapterRegistry());
                    x.AddRegistry(new RepositoryRegistry(serviceLifecycle, connectionString));
                    x.AddRegistry(new ServiceRegistry(serviceLifecycle));                                 
                });

                DependencyContext.CurrentContainer = new DependencyResolverAdapter(CurrentContainer);
                Logger.Log("App started");
            }
            catch (Exception ex)
            {
                try
                {
                    Logger.Log("App failed on start", ex);
                }
                catch (Exception) { }
                throw;
            }
        }

        public static ILogger Logger
        {
            get
            {
                return Resolve<ILogger>();
            }
        }

        public static T Resolve<T>() where T : class
        {
            return (T)CurrentContainer.TryGetInstance(typeof(T));
        }
    }
}
